import { ApiCall } from "tsrpc";
import { BackConfig } from "../../../models/BackConfig";
import { ReqAuth, ResAuth } from "../../../shared/protocols/worldServer/admin/PtlAuth";
import { worldServer } from "../../../WorldServerMain";
import { WorldServerConn } from "../../WorldServer";

export async function ApiAuth(call: ApiCall<ReqAuth, ResAuth>) {
    if (call.req.type === 'MasterServer') {
        let conn = call.conn as WorldServerConn;
        worldServer.masterServerConn = conn;

        conn.masterServer = {
            // 定时 Send State
            intervalSendState: setInterval(() => {
                conn.sendMsg('admin/UpdateSubWorldState', {
                    connNum: worldServer.server.connections.length,
                    subWorlds: worldServer.subWorlds.map(v => v.state)
                })
            }, BackConfig.worldServer.intervalSendState)
        };

        conn.listenMsg('admin/ChatTransform', call => {
            worldServer.broadcastInAllSubWorld(call.msg);
        });

        conn.listenMsg('master/PN', call => {
            let targetId = call.msg.targetId;
            let idType = call.msg.targetIdType;

            call.msg.targetId = undefined;
            call.msg.targetIdType = undefined;

            if (targetId && idType) {
                if (idType == 'subWorldId') {
                    worldServer.id2SubWorld.get(targetId)?.broadcastMsg("master/PN", call.msg);
                }
                else if (idType == 'configId') {
                    worldServer.subWorlds.forEach(v => {
                        if (v.config.id == targetId) {
                            v.broadcastMsg("master/PN", call.msg);
                        }
                    });
                }
                else if (idType == 'userId') {
                    let userConn = worldServer.userId2Conn[targetId];
                    userConn.sendMsg("master/PN", call.msg);
                }
            }
            else {
                worldServer.subWorlds.forEach(v => {
                    v.broadcastMsg("master/PN", call.msg);
                });
            }
        });
    }

    call.succ({});
}